import 'dart:async';
import 'dart:collection';
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/image_network_widget.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/pages/creatTravel/end_travel_tag_widget.dart';
import 'package:jetour_line/pages/creatTravel/end_travel_type_widget.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/double_extension.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../models/jetour_line_detail.dart';
import '../../network/jetour_http.dart';
import 'package:extended_image/extended_image.dart';

import '../../utils/permission_utils.dart';

typedef _EndCallBack = void Function(String img, String caption, bool hasVideo);

class EndTravelScreen extends StatefulWidget {
  JetourDetailModel? detailModel;
  final int id;
  _EndCallBack? endCallBack;

  EndTravelScreen(
      {Key? key, this.detailModel, required this.id, this.endCallBack})
      : super(key: key);

  @override
  State<EndTravelScreen> createState() => _EndTravelScreenState();
}

class _EndTravelScreenState extends State<EndTravelScreen> {
  String? caption, subTitle;
  List images = [];
  final int maxImage = 15;
  ScrollController _scrollController =
      ScrollController(); //创建一个ScrollController

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.detailModel == null) {
      getDetail();
    }
  }

  String? oldText;
  bool isFirst = true;
  bool isUpIng = false;
  int cate = 0;//分类ID
  List<String>? tags;
  @override
  Widget build(BuildContext context) {
    if (isFirst && widget.detailModel != null) {
      images.addAll(widget.detailModel!.videos);
      images.addAll(widget.detailModel!.images);
      caption = widget.detailModel!.caption;
      subTitle = widget.detailModel!.description;
      cate =  widget.detailModel!.cate!;
      tags = widget.detailModel!.tags!;
      isFirst = false;
    }
    return Stack(
      children: [
        BaseScaffold(
            backgroundColor: MyColors.white,
            title: '结束行程',
            body: GestureDetector(
              onTap: (){
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: Container(
                width: double.infinity,
                height: double.infinity,
                color: Colors.transparent,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: SingleChildScrollView(child: Column(children: [
                        Row(
                          children: [
                            SizedBox(
                              width: 32.px,
                            ),
                            Expanded(
                                child: Text(
                                  "添加图片/视频",
                                  style: TextStyle(
                                      fontSize: 32.px,
                                      color: MyColors.color1A1A1A,
                                      fontWeight: FontWeight.w600),
                                )),
                            Text(
                              "视频最大不能高于200M",
                              style: TextStyle(
                                  fontSize: 24.px, color: MyColors.color999999),
                            ),
                            SizedBox(
                              width: 32.px,
                            ),
                          ],
                        ),
                        imgWidget(),
                        SizedBox(
                          height: 32.px,
                        ),
                        Row(
                          children: [
                            SizedBox(
                              width: 32.px,
                            ),
                            Text(
                              '行程标题/描述',
                              style: TextStyle(
                                  fontSize: 32.px, color: MyColors.color1A1A1A),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 32.px,
                        ),
                        captionWidget(),
                        desWidget(),
                        EndTravelTypeWidget(cate:widget.detailModel!.cate!, cateCallBack:  (int id){
                          cate = id;
                        }),
                        EndTravelTagWidget(tags:widget.detailModel!.tags!, tagsCallBack:(value){
                          tags = value;
                        },),
                      ],)),
                    ),

                    bottomWidget()
                  ],
                ),
              ),
            )),
        if (isUpIng)
          Container(
            color: Colors.black26,
            width: double.infinity,
            height: double.infinity,
            child: Center(
              child: CircularProgressIndicator(
                backgroundColor: Colors.white,
                strokeWidth: 4.0,
                valueColor: AlwaysStoppedAnimation<Color>(MyColors.appColor),
              ),
            ),
          )
      ],
    );
  }


  Widget imgWidget() {
    int index = images.length;
    index  = index~/4 ;
    return Container(

      width: double.infinity,
      height:  250.px+200.px*index,
      padding: EdgeInsets.only(left: 32.px, top: 32.px, bottom: 32.px),
      color: MyColors.white,
      child: GridView.extent(
        physics: const NeverScrollableScrollPhysics(),
        //次轴的宽度
        maxCrossAxisExtent: 170.px,
        //次轴的宽度
        padding: const EdgeInsets.all(4.0),
        //上下左右的内边距
        mainAxisSpacing: 4.0,
        //主轴元素间距
        crossAxisSpacing: 4.0,
        //次轴元素间距
        children: [
          for (int i = 0; i < (images.length + 1); i++) imageItemWidget(i),
        ], //添加
      ),
    );
  }

  Widget imageItemWidget(int index) {
    bool isAdd = index == images.length;
    String? image;
    File? imageFile;
    bool isVideo = false;
    bool isVideoUrl = false;
    AssetEntity? assetEntity;
    if (images.isNotEmpty && index < images.length) {
      if (images[index].runtimeType == String) {
        image = images[index];
      } else if (images[index].runtimeType == Videos) {
        Videos video = images[index];
        image = video.frame;
        isVideoUrl = true;
      } else if (images[index].runtimeType == AssetEntity) {
        assetEntity = images[index];
      } else {
        imageFile = images[index];
      }
    }

    if (assetEntity != null &&
        (assetEntity!.type == AssetType.video)) {
      isVideo = true;
    }
    return GestureDetector(
      onTap: () {
        if (isAdd) {
          if (images.length == maxImage) {
            AhaUtils.showTxt('最多选择$maxImage张图片');
          } else {
            selectAssets();
          }
        }
      },
      child: Padding(
        padding: EdgeInsets.only(right: 20.px),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(4.px)),
          child: Container(
              color: MyColors.colorF1F1F1,
              width: 200.px,
              height: 200.px,
              alignment: Alignment.center,
              child: isAdd
                  ? BaseImage(
                      image: 'lsgj_btn_add',
                      width: 60.px,
                      height: 60.px,
                    )
                  : Stack(
                      children: [
                        if (isVideo)
                          SizedBox(
                            width: 200.px,
                            height: 200.px,
                            child: videoWidget(assetEntity!),
                          ),
                        if (!isVideo)
                          Container(
                              child: image == null
                                  ? Image.file(
                                      imageFile!,
                                      fit: BoxFit.cover,
                                      width: 200.px,
                                      height: 200.px,
                                    )
                                  : ImageNetworkWidget(
                                      image,
                                      width: 200.px,
                                      height: 200.px,
                                    )),
                        Positioned(
                          right: 0,
                          top: 0,
                          child: GestureDetector(
                            onTap: () {
                              images.removeAt(index);
                              setState(() {});
                            },
                            child: Container(
                              width: 60.px,
                              height: 60.px,
                              color: Colors.transparent,
                              child: Stack(
                                children: [
                                  Positioned(
                                      right: 0,
                                      top: 0,
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(30.px)),
                                        child: Container(
                                          width: 50.px,
                                          height: 50.px,
                                          color: Colors.black54,
                                        ),
                                      )),
                                  Positioned(
                                      top: 0.px,
                                      right: 0.px,
                                      child: Container(
                                        color: Colors.transparent,
                                        padding: EdgeInsets.only(
                                            right: 10.px, top: 10.px),
                                        alignment: Alignment.topRight,
                                        width: 56.px,
                                        height: 60.px,
                                        child: BaseImage(
                                          image: 'lsgj_btn_closewh',
                                          width: 30.px,
                                          height: 30.px,
                                        ),
                                      )),
                                ],
                              ),
                            ),
                          ),
                        ),
                        if (isVideoUrl)
                          Center(
                            child: BaseImage(
                              image: 'icon_gcvideo',
                              width: 66.px,
                              height: 66.px,
                            ),
                          )
                      ],
                    )),
        ),
      ),
    );
  }

  Widget videoWidget(AssetEntity assetEntity) {
    final AssetEntityImageProvider imageProvider = AssetEntityImageProvider(
      assetEntity!,
      isOriginal: false,
      thumbnailSize: const ThumbnailSize.square(200),
    );
    return Stack(
      children: [
        Positioned(
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            child: ExtendedImage(
              image: imageProvider,
              fit: BoxFit.cover,
            )),
        Center(
          child: BaseImage(
            image: 'icon_gcvideo',
            width: 66.px,
            height: 66.px,
          ),
        )
      ],
    );
  }

  ///选择图片
  Future<void> selectAssets() async {
    PermissionUtils.requestPhotoPickPermission(context, (bool isAgree) async {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
            maxAssets: maxImage - images.length,
            requestType: const RequestType(3),
            textDelegate: const AssetPickerTextDelegate()), ////1 图片 2 视频 3 全部
      ); //File: '/private/var/mobile/Containers/Data/Application/5AF39A3E-2D24-45D4-B178-41B885421182/tmp/.video/1695366559.000000_IMG_0028.MOV'
      for (int i = 0; i < result!.length; i++) {
        AssetEntity assetEntity = result[i];
        File imageFile = await assetEntity.file as File;
        String path = imageFile.path;
        if (assetEntity.type == AssetType.video) {
          images.add(result[i]);
        } else {
          images.add(imageFile);
        }
      }
      // _scrollController.animateTo(images.length * 200.px,
      //     duration: const Duration(milliseconds: 50), curve: Curves.ease);
      setState(() {});
    });


  }

  Widget captionWidget() {
    return Padding(
      padding: EdgeInsets.only(left: 32.px, right: 32.px),
      child: Container(
        width: double.infinity,
        height: 94.px,
        color: MyColors.colorF1F1F1,
        child: Padding(
          padding: EdgeInsets.only(left: 32.px),
          child: TextField(
            onChanged: (value) {
              caption = value;
            },
            decoration: const InputDecoration(
              counterText: '',
              hintText: '填写行程标题',
              border: InputBorder.none,
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
              errorBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
            ),
            controller: TextEditingController.fromValue(TextEditingValue(
                text: caption ?? "", //判断keyword是否为空
                // 保持光标在最后

                selection: TextSelection.fromPosition(TextPosition(
                    affinity: TextAffinity.downstream,
                    offset: '$caption'.length)))),
            style: TextStyle(fontSize: 28.px, color: MyColors.color333333),
            maxLines: 1,
          ),
        ),
      ),
    );
  }

  Widget desWidget() {
    return Padding(
      padding: EdgeInsets.only(left: 32.px, right: 32.px, top: 32.px),
      child: Container(
        width: double.infinity,
        height: 280.px,
        color: MyColors.colorF1F1F1,
        child: Padding(
          padding: EdgeInsets.only(left: 32.px,right: 32.px),
          child: TextField(
              onChanged: (value) {
                subTitle = value;
              },
              maxLength: 150,
              maxLines: 6,
              controller: TextEditingController.fromValue(TextEditingValue(
                  text: subTitle ?? "", //判断keyword是否为空
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: '$subTitle'.length)))),
              decoration: const InputDecoration(
                hintText: '填写行程描述',
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
              ),
              style: TextStyle(fontSize: 28.px, color: MyColors.color333333)),
        ),
      ),
    );
  }

  Widget bottomWidget() {
    return Padding(
      padding: EdgeInsets.all(32.px),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(40.px)),
            child: GestureDetector(
              onTap: () {
                saveTravel(false);
              },
              child: Container(
                alignment: Alignment.center,
                width: 170.px,
                height: 80.px,
                color: MyColors.colorF1F1F1,
                child: Text(
                  '存草稿',
                  style:
                      TextStyle(fontSize: 30.px, color: MyColors.color999999),
                ),
              ),
            ),
          ),
          SizedBox(
            width: 32.px,
          ),
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(40.px)),
              child: GestureDetector(
                onTap: () {
                  saveTravel(true);
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 80.px,
                  color: MyColors.color00A198,
                  child: Text(
                    '发布行程',
                    style: TextStyle(fontSize: 30.px, color: MyColors.white),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<void> saveTravel(bool isPublish) async {
    String? msg;
    if (images.isEmpty) {
      msg = '请选择照片';
    } else if (caption == null || caption!.isEmpty) {
      msg = '请输入行程标题';
    } else if (subTitle == null || subTitle!.isEmpty) {
      msg = '请输入行程描述';
    }
    if (msg != null) {
      AhaUtils.showTxt(msg);
    } else {
      for (int i = 0; i < images.length; i++) {
        if (images[i].runtimeType == AssetEntity) {
          AssetEntity assetEntity = images[i];
          File? file = await assetEntity.file;
          if (file!.lengthSync() > 104857600 * 2) {
            AhaUtils.showTxt('当前视频文件过大，请编辑视频后再次上传');
            return;
          }
        }
      }
      List fileUrl = await fetchData();
      List<String> imageUrls = [];
      List videos = [];
      for (int i = 0; i < fileUrl.length; i++) {
        if (fileUrl[i].runtimeType == String) {
          String url = fileUrl[i];
          imageUrls.add(url);
        } else {
          videos.add(fileUrl[i]);
        }
      }
      print('saveTravel2$imageUrls');
      Map<String, dynamic> map = Map();
      map['id'] = widget.id;
      map['caption'] = caption;
      map['description'] = subTitle;
      map['images'] = imageUrls;
      map['videos'] = videos;
      map['publish'] = isPublish ? '1' : '0'; //1、发布路书 0、存草稿
      if(cate>0){
        map['cate'] = cate;
      }if(tags!.isNotEmpty){
        map['tags'] = tags;
      }
      print('GuideFinishLine$map');
      JetourHttp().post(JetourRouter.GuideFinishLine, data: map).then((value) {
        isUpIng = false;
        setState(() {});
        if (value == null) {
          return;
        }
        if (widget.endCallBack != null) {
          if (imageUrls.isNotEmpty) {
            widget.endCallBack!(imageUrls.first, caption!, !videos.isEmpty);
          }
        }
        if (isPublish) {
          AhaUtils.showTxt("发布成功");
        } else {
          AhaUtils.showTxt("保存草稿成功");
        }
        Future.delayed(const Duration(seconds: 1), () {
          Navigator.pop(context, 'publish');
        });
      });
    }
  }

  ///上传视频  图片
  Future<List> fetchData() async {
    isUpIng = true;
    setState(() {});
    var completer = Completer<List<dynamic>>();
    List imageUrls = [];
    List<Future> awaitRequest = [];
    try {
      for (int i = 0; i < images.length; i++) {
        if (images[i].runtimeType == AssetEntity ||
            images[i].runtimeType == Videos) {
          var url = JetourHttp().upVideo(images[i]);
          awaitRequest.add(url);
          // imageUrls.add(url);
        }
      }
      List upImg = [];
      for (int i = 0; i < images.length; i++) {
        if (images[i].runtimeType != AssetEntity &&
            images[i].runtimeType != Videos) {
          upImg.add(images[i]);
        }
      }
      if (upImg.isNotEmpty) {
        var imgs = JetourHttp().upImages(upImg);
        awaitRequest.add(imgs);
        // List<String> imageUrls = await JetourHttp().upImages(images);
        // imageUrls.addAll(imageUrls);
      }

      Future.wait(awaitRequest).then((results) {
        completer.complete(results);
      });
      List results = await completer.future;
      for (int i = 0; i < results.length; i++) {
        if (results[i].runtimeType == List<String>) {
          imageUrls.addAll(results[i]);
        } else {
          imageUrls.add(results[i]);
        }
      }
      print("imageUrls = $imageUrls");
      return imageUrls;
    } catch (e) {
      print('Error: $e');
      return [];
    }
  }

  void getDetail() {
    Map<String, dynamic> map = Map();
    map['id'] = widget.id;
    JetourHttp().get(JetourRouter.GuideToolDetail, params: map).then((value) {
      print('getDetailgetDetail$value');
      widget.detailModel = JetourDetailModel.fromJson(value);
      setState(() {});
    });
  }
}
